import React, { Component } from "react";
import { View, Alert } from "react-native";
import CustomHeader from "../../components/CustomHeader";
import QRCodeScanner from "react-native-qrcode-scanner";
import { request } from "../../utils";

export class ScanScreen extends Component {
  onSuccess = ({ data }) => {
    console.log("data", data);
    try {
      data = JSON.parse(data);
      switch (data.qType) {
        case "person":
          this.scanPersonSuccess(data);
          break;
      }
    } catch (error) {
      Alert.alert(error);
    }
  };
  scanPersonSuccess = data => {
    const { pId, pName } = data;
    const { navigation } = this.props;
    request(
      "person/addGuardian",
      { pId },
      _ => {
        console.log("scan success");
        Alert.alert("已经成为 " + pName + " 的监护人", "", [
          {
            text: "确定",
            onPress: _ => {
              navigation.goBack();
            }
          }
        ]);
        // this.scanner.reactivate();
      },
      data => {
        console.log("scan fail");
        Alert.alert(data, "", [
          { text: "确定", onPress: _ => navigation.goBack() }
        ]);
        // this.scanner.reactivate();
      }
    );
  };
  render() {
    return (
      <View>
        <CustomHeader title="扫描二维码" />
        <QRCodeScanner
          ref={ref => (this.scanner = ref)}
          cameraStyle={{
            marginTop: 68
          }}
          onRead={this.onSuccess}
          showMarker={true}
          checkAndroid6Permissions={true}
        />
      </View>
    );
  }
}

export default ScanScreen;
